# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""

from googletrans import Translator
#import time
import os
import random

baseDir = '/root/workdir/gitdir/linuxcmd/'

#函数写在前面
def formatEnTxt(fcmd):
    '''
    格式化英文文档,去掉折行
    '''
    enTxt = open('{0}/other/english-txt/{1}.en.txt'.format(baseDir,fcmd),'r')
    lines = enTxt.readlines()
    enTxt.close()
    
    enTxt = open('{0}/other/english-txt/{1}.en.txt'.format(baseDir,fcmd),'w')
    
    idx = 0
    while(idx < len(lines)):
        #print(lines[idx],'处理第一个文档')
        #第一句翻译
        
        if idx > len(lines)-2:  #最后一句不翻译
            enTxt.write(lines[idx])
            idx += 1
        else:
            #合并两句
            if len(lines[idx]) >= 70 and len(lines[idx+1].strip()) != 0:
                string = lines[idx].rstrip() + lines[idx+1].lstrip()
                enTxt.write(string)
                idx += 1
                # print(string)
            
            # -h xxx 这中格式的行,分成两行
            elif len(lines[idx]) >=15 and lines[idx][7] == '-' and  lines[idx][9] == ' ' and  lines[idx][10] == ' ' and  lines[idx][11] == ' ':
                    seq1 = lines[idx][0:9]
                    seq2 = lines[idx][9:]
                    #print(seq1)
                    enTxt.write(seq1)
                    enTxt.write('\n')
                    enTxt.write('        ')
                    enTxt.write(seq2)
                    enTxt.write('\n')                      
            else:
                enTxt.write(lines[idx])
    
            idx += 1
            
    enTxt.close()
    
#改变目录
os.chdir("{0}/other/english-txt/".format(baseDir))

#列出目录下所有文件名
cmdList = os.listdir("{0}/other/english-txt/".format(baseDir))  #将该目录下的的所有文件名称存入列表txtList
cmdList.sort()   # 显示当前文件夹下所有文件并进行排序
cmdNum = len(cmdList)

#预处理文本，去掉换行符
for j in cmdList:
    print(j)
    j = j[:-7]
    for i in range(5):
        formatEnTxt(j)


#去除已经翻译的文档
zhCNList = os.listdir("{0}/other/zh-CN/".format(baseDir))  #将该目录下的的所有文件名称存入列表txtList
zhCNList = [i[:-10] for i in zhCNList]
zhCNList.sort()   # 显示当前文件夹下所有文件并进行排序

#cnNum = len(os.listdir('{0}/zh-CN/'.format(baseDir)))  #将该目录下的的所有文件名称存入列表txtList



tag1 = 0
#循环批量处理
for idx,iterm in enumerate(cmdList):

    
    #去掉后缀
    cmd = iterm[:-7]
    
    #print(cmd)
    #读取中文已经翻译的文档,如果不存在直接创建,如果存在判断是否完全翻译.主要是中断引起的不完全翻译
    try:
        zhTxt = open('{0}/other/zh-CN/{1}.zh-CN.txt'.format(baseDir,cmd),'r')
        zhlines = zhTxt.readlines()
        zhTxt.close()
    except FileNotFoundError:
        zhlines = ''
            
    if len(zhlines) != 0:
        #判断是否完全翻译,如果最后一句是下面字符串,则翻译完全
        if zhlines[-1] == '远风 <zki@163.com> www.linuxcmd.com.cn 2020-08-03':
            tag1 = 1
    
        
    if  tag1 == 1: #对已经翻译的文档不再进行翻译
        print(cmd,'cmd在zhCNlist中不进行翻译****')
        tag1 = 0
        continue
    
    print(cmd,"进行翻译")
    

        

    
    
    translator = Translator(service_urls=['translate.google.cn'])
    
    enTxt = open('{0}/other/english-txt/{1}.en.txt'.format(baseDir,cmd),'r')
    lines = enTxt.readlines()
    enTxt.close()
    
    cnTxt = open('{0}/other/zh-CN/{1}.zh-CN.txt'.format(baseDir,cmd),'w')
    cnTxt.write(cmd)
    cnTxt.write('\n')
    cnTxt.write('\n')
    cnTxt.write('请校正该命令')
    cnTxt.write('\n')
    cnTxt.write('\n')
    cnTxt.write('##################################')
    cnTxt.write('\n')
    cnTxt.write('\n')
    #插入前三句
    
    keyWordsDict = {'':'','\n':'\n','NOTE':'NOTE(注意)','AUTHOR':'AUTHOR(作者)','WARNING':'WARNING(注意)','VARIABLES':'VARIABLES(变量)','RETURN CODES':'RETURN CODES(返回码)','NOTES':'NOTES(注意)','COPYRIGHT':'COPYRIGHT(版权)','USE':'USE(用法)','SUMMARY':'SUMMARY(摘要)','OUTPUT':'OUTPUT(输出)','Usage':'Usage(用法)','EXAMPLES':'EXAMPLES(示例)','DIAGNOSTICS':'DIAGNOSTICS(诊断)','ACKNOWLEDGEMENTS':'ACKNOWLEDGEMENTS(致谢)','NAME':'NAME(名称)','SYNOPSIS':'SYNOPSIS(概要)','DESCRIPTION':'DESCRIPTION(描述)','OPTIONS':'OPTIONS(选项)','SEE ALSO':'SEE ALSO(另见)','CAVEATS':'CAVEATS(不足)','BUGS':'BUGS','EXIT STATUS':'EXIT STATUS(退出状态码)','ENVIRONMENT':'ENVIRONMENT(环境变量)','FILES':'FILES(配置文件)','AUTHORS':'AUTHORS(作者)','AVAILABILITY':'AVAILABILITY(可获得)'}
    keyWordKeys = list(keyWordsDict.keys())
    #开始进行翻译
   # print(keyWordKeys)

    global tag, tag2, tag3, tag4
    tag=0
    tag2=0
    tag3=0
    tag4=0
    
    for line in lines:

       # print('执行成功')
        if line[0] != '':
            keyWordsDict[line] = ''
        
        spaceLine = line #没有去掉空格的行
        
        line = line.strip()  #去掉字符串两端的空格
        
        #source =line
        if line in keyWordKeys:
            cnTxt.write(keyWordsDict[line])
            cnTxt.write('\n')
            if len(line) >= 1 and line in ['SYNOPSIS','COPYRIGHT','SEE ALSO','AUTHORS','AUTHOR']:
                tag2 = 1
            elif line in ['AUTHOR','NOTE', 'WARNING', 'VARIABLES', 'RETURN CODES', 'NOTES', 'COPYRIGHT', 'USE', 'SUMMARY', 'OUTPUT', 'Usage', 'EXAMPLES', 'DIAGNOSTICS', 'ACKNOWLEDGEMENTS', 'NAME', 'SYNOPSIS', 'DESCRIPTION', 'OPTIONS', 'SEE ALSO', 'CAVEATS', 'BUGS', 'EXIT STATUS', 'ENVIRONMENT', 'FILES', 'AUTHORS', 'AVAILABILITY']:
                tag2 = 0
                    
        else:
            if line[0] == '-':
                cnTxt.write('    ')
                cnTxt.write(line)
                cnTxt.write('\n')  
                
                tag = 1
            else:
                if tag == 1:
                    cnTxt.write('    ')
                    tag = 0
                
                if tag2 == 1:
                    cnTxt.write('    ')
                    cnTxt.write(line)        
                    cnTxt.write('\n')
                    
                else:
                    cnTxt.write('    ')
                    text = translator.translate(line,src='en',dest='zh-cn').text
                    print(text)
                    
                    cnTxt.write(text)        
                    cnTxt.write('\n')
                

                
        secondList = [0.1,0.5,0.5,1,2,3,1,2,0.6,0.7,0.8,0.9,0.5,0.6,0.4,1,2,3]
        lab = random.randint(0,len(secondList)-1)
        #time.sleep(secondList[lab])
        
    cnTxt.write('\n')
    cnTxt.write('远风 <zki@163.com> www.linuxcmd.com.cn 2020-08-03')
    cnTxt.close()
    


